﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Build.BuildEngine;
using Microsoft.Build.Framework;
using System.IO;
using Deployment.BuildManager.ExternalProcess.Common;

namespace Deployment.BuildManager.ExternalProcess.Compiler
{
    public class BuildTask : IBuildTask
    {
        #region IBuildTask Members

        public SetupInfo Execute(SetupInfo info)
        {
            try
            {
                this.BuildSetupPackager(info);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return info;
        }

        public void Cancel()
        {
            throw new NotImplementedException();
        }

        #endregion

        #region Private Methods

        private bool BuildSetupPackager(SetupInfo info)
        {
            this.SendMessage("Empacotando...");

            string logPath = Path.Combine(Path.GetDirectoryName(info.LogFilePath), BuildConstants.BuildPackageLogFile);

            if (!Directory.Exists(info.LogFilePath))
                Directory.CreateDirectory(info.LogFilePath);

            FileLogger logger = new FileLogger();
            logger.Parameters = @"logfile=" + logPath;

            string projectFile = info.SetupTemplateProjectPath + Path.DirectorySeparatorChar + BuildConstants.SetupTemplateCsProjName;

            bool flag = false;

            Engine engine = new Engine();
            engine.RegisterLogger(logger);

            try
            {
                Project project = null;
                project = new Project(engine);
                project.Load(projectFile);
                project.GlobalProperties.SetProperty("Configuration", "Release");
                project.GlobalProperties.SetProperty("OutputPath", @"..\Compilados\");

                flag = engine.BuildProject(project);

                if (flag)
                    DeleteObjFolder(info);

                return flag;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void DeleteObjFolder(SetupInfo info)
        {
            string objFolder = info.SetupTemplateProjectPath + Path.DirectorySeparatorChar + "obj";
            if (Directory.Exists(objFolder))
                Directory.Delete(objFolder, true);
        }

        #endregion

        #region [ Events ]

        public event EventHandler<MessageEventArgs> MessageReceived;

        private void SendMessage(string message)
        {
            if (MessageReceived != null)
            {
                MessageEventArgs eventArgs = new MessageEventArgs(message);
                Logger.Log(message, Logger.EntryType.Information);
                MessageReceived(this, eventArgs);
            }
        }

        #endregion [ Events ]
    }
}
